<template>
  <div>
    <!-- 可上下拖拽悬浮球 -->
    <div
      class="floating-ball"
      :style="{
        bottom: ballBottom + 'px',
        right: ballRight + 'px',
        cursor: isDragging ? 'grabbing' : 'grab'
      }"
      @mousedown="startDrag"
      @click.stop="toggleSearch"
    >
      <i class="el-icon-search"></i>
    </div>

    <!-- 搜索框 -->
    <div
      class="search-container"
      :class="{active: showSearch}"
      :style="{bottom: ballBottom + 'px', right: ballRight + 'px'}"
    >
      <el-input
        v-model="searchText"
        placeholder="输入偶像姓名进行搜索..."
        size="small"
        @keyup.enter.native="handleSearch"
      ></el-input>
      <el-button
        type="primary"
        size="small"
        @click="handleSearch"
        :loading="loading"
      >搜索</el-button>
      <i class="el-icon-close close-search" @click="toggleSearch"></i>
    </div>

    <!-- 偶像信息对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="60%"
      top="5vh"
      custom-class="simple-idol-dialog"
    >
      <div class="simple-idol-card">
        <!-- 头像和基本信息 -->
        <div class="simple-idol-header">
          <div class="simple-idol-avatar">
            <img :src="currentIdol.avatar || 'https://tse2.mm.bing.net/th/id/OIP.2b_rt8JNhLflvzhgZ0ni8gHaLH?rs=1&pid=ImgDetMain&o=7&rm=3'" :alt="currentIdol.罗马拼音 || currentIdol.本名">
          </div>
          <div class="simple-idol-name">
            <h2>{{ currentIdol.罗马拼音 || currentIdol.本名 }}</h2>
            <p v-if="currentIdol.昵称">昵称: {{ currentIdol.昵称 }}</p>
          </div>
        </div>

        <!-- 所有信息平铺展示 -->
        <div class="simple-idol-details">
          <div
            class="simple-detail-item"
            v-for="(value, key) in currentIdol"
            :key="key"
            v-if="!['罗马拼音', '本名', '昵称', 'avatar'].includes(key)"
          >
            <div class="simple-detail-label">{{ key }}:</div>
            <div class="simple-detail-value">
              <template v-if="isArrayLike(value)">
                <el-tag
                  v-for="(item, index) in splitValue(value)"
                  :key="index"
                  size="small"
                  style="margin-right: 5px; margin-bottom: 5px;"
                >{{ item }}</el-tag>
              </template>
              <template v-else>
                {{ value }}
              </template>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'IntegratedFloatingSearch',
  props: {
    // 初始位置
    initialBottom: {
      type: Number,
      default: 30
    },
    initialRight: {
      type: Number,
      default: 30
    },
    // API基础URL
    apiBaseUrl: {
      type: String,
      default: 'http://127.0.0.1:8000'
    }
  },
  data() {
    return {
      ballBottom: this.initialBottom,
      ballRight: this.initialRight,
      showSearch: false,
      searchText: '',
      dialogVisible: false,
      currentIdol: {},
      loading: false,
      isDragging: false,
      startY: 0,
      startBottom: 0
    }
  },
  computed: {
    dialogTitle() {
      return this.currentIdol.罗马拼音 || this.currentIdol.本名 || '偶像信息'
    }
  },
  mounted() {
    // 添加全局事件监听
    document.addEventListener('mousemove', this.handleDrag)
    document.addEventListener('mouseup', this.stopDrag)

    // 从本地存储读取位置
    const savedPos = localStorage.getItem('floatingBallPosition')
    if (savedPos) {
      const { bottom, right } = JSON.parse(savedPos)
      this.ballBottom = bottom
      this.ballRight = right
    }
  },
  beforeDestroy() {
    // 移除事件监听
    document.removeEventListener('mousemove', this.handleDrag)
    document.removeEventListener('mouseup', this.stopDrag)
  },
  methods: {
    startDrag(e) {
      // 如果点击的是搜索框内的元素，不触发拖拽
      if (e.target.closest('.search-container')) {
        return
      }

      this.isDragging = true
      this.startY = e.clientY
      this.startBottom = this.ballBottom
      e.preventDefault()
    },
    handleDrag(e) {
      if (!this.isDragging) return

      const dy = e.clientY - this.startY

      // 修复方向相反的问题：鼠标向下移动时，ballBottom应该减小
      this.ballBottom = Math.max(10, Math.min(window.innerHeight - 60, this.startBottom - dy))
    },
    stopDrag() {
      if (!this.isDragging) return

      this.isDragging = false
      // 保存位置到本地存储
      localStorage.setItem('floatingBallPosition', JSON.stringify({
        bottom: this.ballBottom,
        right: this.ballRight
      }))
    },
    toggleSearch(e) {
      // 如果是拖拽结束的点击，不触发搜索框
      if (this.isDragging) {
        this.isDragging = false
        return
      }

      this.showSearch = !this.showSearch
      if (this.showSearch) {
        this.$nextTick(() => {
          this.$el.querySelector('.search-container input').focus()
        })
      }
    },
    async handleSearch() {
      if (!this.searchText.trim()) {
        this.$message.warning('请输入搜索内容')
        return
      }

      this.loading = true
      try {
        const response = await axios.get(`${this.apiBaseUrl}/idol/info/${encodeURIComponent(this.searchText)}`)

        if (response.data.code === 618 && response.data.data) {
          this.currentIdol = response.data.data
          this.dialogVisible = true
          this.showSearch = false
          this.searchText = ''
        } else {
          this.$message.error(response.data.message || '未找到匹配的偶像信息')
        }
      } catch (error) {
        this.$message.error('搜索失败: ' + error.message)
      } finally {
        this.loading = false
      }
    },
    isArrayLike(value) {
      if (!value || typeof value !== 'string') return false
      return /[、,，]/.test(value) || /《/.test(value)
    },
    splitValue(value) {
      if (!value) return []

      // 处理《》格式的作品
      if (/《/.test(value)) {
        return value.split('《')
          .filter(item => item.includes('》'))
          .map(item => item.split('》')[0])
          .filter(item => item)
      }

      // 处理普通分隔符
      return value.split(/[、,，]/).map(item => item.trim()).filter(item => item)
    }
  }
}
</script>

<style scoped>
/* 样式保持不变 */
.floating-ball {
  position: fixed;
  width: 50px;
  height: 50px;
  background: linear-gradient(135deg, #ff7e5f, #feb47b);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 2000;
  transition: transform 0.2s, box-shadow 0.2s;
  user-select: none;
}

.floating-ball:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
}

.floating-ball i {
  color: white;
  font-size: 20px;
  pointer-events: none;
}

.search-container {
  position: fixed;
  background: white;
  border-radius: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  padding: 8px 12px;
  display: flex;
  align-items: center;
  z-index: 2000;
  transition: all 0.3s ease;
  opacity: 0;
  transform: translateY(20px);
  pointer-events: none;
}

.search-container.active {
  opacity: 1;
  transform: translateY(0);
  pointer-events: auto;
}

.search-container >>> .el-input {
  width: 200px;
}

.search-container >>> .el-input__inner {
  border-radius: 15px;
  border: none;
  background: #f5f7fa;
}

.search-container >>> .el-button {
  margin-left: 8px;
  border-radius: 15px;
}

.close-search {
  margin-left: 10px;
  cursor: pointer;
  color: #909399;
  font-size: 16px;
  transition: color 0.3s;
}

.close-search:hover {
  color: #ff7e5f;
}

/* 简单偶像卡片样式 */
.simple-idol-card {
  padding: 0;
}

.simple-idol-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.simple-idol-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 20px;
  border: 2px solid #f0f2f5;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.simple-idol-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.simple-idol-name h2 {
  font-size: 22px;
  color: #303133;
  margin-bottom: 5px;
}

.simple-idol-name p {
  color: #606266;
  font-size: 14px;
}

.simple-idol-details {
  max-height: 60vh;
  overflow-y: auto;
}

.simple-detail-item {
  margin-bottom: 15px;
  display: flex;
}

.simple-detail-label {
  width: 100px;
  color: #909399;
  font-size: 14px;
  flex-shrink: 0;
}

.simple-detail-value {
  flex: 1;
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
}

/* 对话框样式 */
>>> .simple-idol-dialog {
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

>>> .simple-idol-dialog .el-dialog__body {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

>>> .simple-idol-dialog .el-dialog__header {
  border-bottom: 1px solid #ebeef5;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .simple-idol-header {
    flex-direction: column;
    text-align: center;
  }

  .simple-idol-avatar {
    margin-right: 0;
    margin-bottom: 15px;
  }

  .simple-detail-item {
    flex-direction: column;
  }

  .simple-detail-label {
    width: auto;
    margin-bottom: 4px;
  }
}
</style>
